//
//  MYXLukcyMoneyDetailViewController.m
//  meiyinxiang
//
//  Created by apple on 2017/11/9.
//  Copyright © 2017年 hbjApple. All rights reserved.
//

#import "MYXLukcyMoneyDetailViewController.h"
#import "MediaImpressViewController.h"
#import "MYXRecommendDetailController.h"

#import <MJRefresh.h>
#import <HexColor.h>
//cell
#import "LukyMoneyDetailContentCell.h"
#import "GetLuckyMoneyListCell.h"
#import "RecievedLukcyDetailTableViewCell.h"
#import "RecievedSectionView.h"
#import "MYXRecieveMoneyListViewModel.h"

@interface MYXLukcyMoneyDetailViewController ()
<UITableViewDelegate,
UITableViewDataSource>
{
    CGFloat lastOriginalY;
    LukyMoneyDetailContentCell *contenCell ;
    RecievedLukcyDetailTableViewCell *recievedDetailCell;
    UITextField *leaveMessageTextField;

}
@property (nonatomic,strong) UITableView *tableView;
@end

@implementation MYXLukcyMoneyDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self configTableView];
    [self addRefresh];
    AdjustsScrollViewInsetNever(self, self.tableView);
    //添加5秒广告和评论成功通知
    [self addCommendRefresh];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [self add5SecondTimeRefresh];

}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.detailviewModel hidekeybord];
    self.navigationController.navigationBarHidden = NO;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:Post5SecondSucessNotificationName object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:PostCommendSucessNOtificationName object:nil];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self postRefreshNotice];
    [contenCell deleteTimer];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:Post5SecondSucessNotificationName object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:PostCommendSucessNOtificationName object:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark -PrivateMethod
- (void)setModel:(MXYLuckymoneyViewModel *)model{
    _model = model;
    self.detailviewModel = model.viewModel;
}
- (void)setDetailviewModel:(MYXDetailViewModel *)detailviewModel{
    _detailviewModel = detailviewModel;
}
- (void)add5SecondTimeRefresh{//5秒后刷新数据
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTime) name:Post5SecondSucessNotificationName object:nil];
}
- (void)addCommendRefresh{//评论成功刷新数据
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshRecommendCell) name:PostCommendSucessNOtificationName object:nil];
}
- (void)refreshRecommendCell{
    NSIndexSet *set = [NSIndexSet indexSetWithIndex:1];
    self.detailviewModel.comment_status = @"1";
    [self.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationFade];
}
- (void)refreshTime{
    NSLog(@"5 second is comming");
    WS(weakSelf);
    [self.model getMoneyDetailWithIsPullup:NO Completion:^(BOOL success, NSString *message) {
        if (success) {
            weakSelf.detailviewModel = weakSelf.model.viewModel;
            [weakSelf.tableView reloadData];
        }
        weakSelf.detailviewModel.isSecondRefresh = YES;
    }];
   
}
- (void)addRefresh{
    WS(weakSelf);
    //上拉加载更多
    NSIndexSet *set = [NSIndexSet indexSetWithIndex:1];
  
    self.tableView.mj_footer  =   [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf.detailviewModel getMoneyDetailWithIsPullup:YES Completion:^(BOOL success, NSString *message) {
            if (success) {
                [weakSelf.tableView reloadData];
                [weakSelf.tableView.mj_footer endRefreshing];
            }else{
                [weakSelf.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationFade];
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }];
    }];
}

- (void)configTableView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor colorWithHexString:@"f2f2f2"];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@(0));
        make.left.equalTo(@0);
        make.right.equalTo(@0);
        make.bottom.equalTo(@0);
    }];
    [self.tableView registerNib:[UINib nibWithNibName:@"LukyMoneyDetailContentCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:LukyMoneyDetailContentCellReuseId];
    [self.tableView registerNib:[UINib nibWithNibName:@"GetLuckyMoneyListCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:GetLuckyMoneyListCellResuId];
    [self.tableView registerNib:[UINib nibWithNibName:@"RecievedSectionView" bundle:[NSBundle mainBundle]] forHeaderFooterViewReuseIdentifier:ReceiveSectionReuseId];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"RecievedLukcyDetailTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:RecievedLukcyDetailReuseId];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark -UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return self.detailviewModel.marray.count > 0 ? _detailviewModel.marray.count : _detailviewModel.list.count;
    }
    return 0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {

            contenCell = [tableView dequeueReusableCellWithIdentifier:LukyMoneyDetailContentCellReuseId forIndexPath:indexPath];
            if (contenCell == nil) {
                contenCell = [LukyMoneyDetailContentCell loadNibWithLukyMoneyDetailContentCell];
            }
            contenCell.mSuperVC = self;
            [contenCell.backBtn addTarget:self action:@selector(backAct) forControlEvents:UIControlEventTouchUpInside];
            contenCell.detailModel = self.detailviewModel;
            //10秒广告结束
            __weak typeof(self) weakself = self;
            contenCell.adfinshBlock = ^{
                        dispatch_async(dispatch_get_main_queue(), ^{
                    [weakself.tableView reloadData];
                });
                
            };
            contenCell.detailModel.singleImgFinishBlock= ^(BOOL isdone){
                if (isdone) {
                    NSIndexSet *set = [NSIndexSet indexSetWithIndex:0];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakself.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationFade];
                    });
                }
            };
            return contenCell;
     
    }else{
        GetLuckyMoneyListCell *listCell = [tableView dequeueReusableCellWithIdentifier:GetLuckyMoneyListCellResuId forIndexPath:indexPath];
        if (listCell == nil) {
            listCell = [GetLuckyMoneyListCell loadNibWithListCell];
        }
        MYXRecieveMoneyListViewModel *detailModel = [self.detailviewModel.marray objectAtIndex:indexPath.row] ;
        listCell.detailModel = detailModel;
        return listCell;
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return self.detailviewModel.cellHeight;
    }else{
        MYXRecieveMoneyListViewModel *listViewModel = self.detailviewModel.marray[indexPath.row];
        return listViewModel.cellHeight;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.01;
    }
    return 25;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        RecievedSectionView *sectionView = [RecievedSectionView loadNibSectionView];
        sectionView.detailModel = self.detailviewModel;
        return sectionView;
    }else{
        return nil;
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //NSLog(@"scrollview offset %f",scrollView.contentOffset.y);
    [self.detailviewModel hidekeybord];
    lastOriginalY = scrollView.contentOffset.y;
    CGFloat consTop;
    CGFloat height;
    if (lastOriginalY < 0) {
       consTop  = - lastOriginalY;
        height = - lastOriginalY + 110;
    }else{
        consTop = 0;
        height = 110;
    }
    if (contenCell) {
        contenCell.topCons.constant = -consTop;
        contenCell.bgheightCons.constant = height;
    }
    if (recievedDetailCell) {
        recievedDetailCell.topCons.constant = -consTop;
        recievedDetailCell.bgheightCons.constant = height;
    }
   
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.model.viewModel hidekeybord];
    UITableViewCell *selectCell = [tableView cellForRowAtIndexPath:indexPath];
    MYXRecieveMoneyListViewModel *detailModel = [self.detailviewModel.marray objectAtIndex:indexPath.row] ;

    if ([selectCell isKindOfClass:[GetLuckyMoneyListCell class]] && detailModel.content.length > 0) {
        MYXRecommendDetailController *recommendDetailVC = [[MYXRecommendDetailController alloc] init];
        recommendDetailVC.redPacketId = detailModel.cateLuckyMoneyId;
        recommendDetailVC.commentManId = detailModel.tid;
        [self.navigationController pushViewController:recommendDetailVC animated:YES];
    }
}
#pragma mark -PrivateMethod
- (void)backAct{
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)postRefreshNotice{
    [[NSNotificationCenter defaultCenter] postNotificationName:RFRESH_LuckyMoneyList object:nil];
}



@end
